package com.forotuxpan.appforotuxpan;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Fragment;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link NoticiasFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link NoticiasFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NoticiasFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    //private AdView adView;
    Boolean isErrorConnec = false;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Noticias.
     */
    // TODO: Rename and change types and number of parameters
    public static NoticiasFragment newInstance(String param1, String param2) {
        NoticiasFragment fragment = new NoticiasFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public NoticiasFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_noticias, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onActivityCreated(Bundle state) {
        super.onActivityCreated(state);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        if (isOnline()) {
            GetCategorias();
        }
        else
        {
            Toast.makeText(getActivity(), getResources().getString(R.string.msg_no_conexion), Toast.LENGTH_SHORT).show();
        }
        ListView lstListado = (ListView)getView().findViewById(R.id.LstCategorias);
        lstListado.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    //if (((Categoria)parent.getItemAtPosition(position)).getNumProveedores() > 0) {
                        Intent i = new Intent(view.getContext(), NoticiasCategoriaActivity.class);
                        i.putExtra("NombreCategoria", ((Categoria) parent.getItemAtPosition(position)).getNombreCategoria());
                        startActivity(i);
                    //}
                    //else {
                    //    Toast.makeText(getActivity(), getResources().getString(R.string.msg_no_existen_provee), Toast.LENGTH_SHORT).show();
                    //}
                }
                catch (Exception e)
                {
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        //adView = new AdView(getActivity());
        //adView.setAdUnitId(MY_AD_UNIT_ID);
        //adView.setAdSize(AdSize.BANNER);
        //FrameLayout layout = (FrameLayout)getView().findViewById(R.id.flCategorias);
        //layout.addView(adView);
        //AdRequest adRequest = new AdRequest.Builder()
        //        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)       // Emulator
        //        .addTestDevice("317C00060000000101608BC10701E015") // My test phone
        //        .build();
        //adView.loadAd(adRequest);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (task != null) {
            if (task.getStatus() == AsyncTask.Status.RUNNING) {
                task.cancel(true);
            }
        }
    }

    public void GetCategorias() {
        //mCallbacks.showCargando();
        //ArrayList categorias = FromJSONtoArrayList_Categorias();

        task = new AsyncTask<Void, Void, Void>() {
            ArrayList categorias;
            @Override
            protected void onPreExecute() {
                showLoading(getActivity());
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    categorias = FromJSONtoArrayList_Categorias();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isErrorConnec) {
                                Toast.makeText(getActivity(), getResources().getString(R.string.msg_problema_conexion), Toast.LENGTH_LONG).show();
                            }
                            else {
                                ListView listView1 = (ListView) getView().findViewById(R.id.LstCategorias);
                                listView1.setAdapter(new ItemAdapterCategoria(listView1.getContext(), categorias));
                            }
                        }
                    });
                }
                /*catch (InterruptedException e) {
                    //e.printStackTrace();
                    mCallbacks.hiddenCargando();
                }*/
                catch (Exception ex) {
                    hiddenLoading();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                hiddenLoading();
            }

        };
        //task.execute((Void[])null);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            task.execute((Void[]) null);
    }

    public ArrayList FromJSONtoArrayList_Categorias() {
        ArrayList listItems = new ArrayList();

        try {
            isErrorConnec = false;
            // Replace it with your own WCF service path
            URL json = new URL("http://serviciosandroid.forotuxpan.com/wsAndroid/get_categorias_noticias.php");
            URLConnection jc = json.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

            String line = reader.readLine();

            JSONObject jsonResponse = new JSONObject(line);
            JSONArray jsonArray = jsonResponse.getJSONArray("Categorias");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jObject = (JSONObject)jsonArray.get(i);
                // "FullName" is the property of .NET object spGetPersonsResult,
                // and also the name of column in SQL Server 2008
                listItems.add(new Categoria(jObject.getString("NombreCategoria")));
            }

            reader.close();

        }catch(Exception e){
            //Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
            //Toast.makeText(getActivity(), "Servicio no disponible, intente mas tarde.", Toast.LENGTH_LONG).show();
            isErrorConnec = true;
            Log.d("Error Categorias:", e.getMessage());
        }

        return listItems;
    }

    private boolean isOnline()
    {
        ConnectivityManager cm= (ConnectivityManager) getView().getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnected();

    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onRemoveFragmet(int idFragmet);
    }

}
